package com.sgzn.sgpay.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.sgzn.sgpay.enums.SgsResponseCode;
import com.sgzn.sgpay.model.request.SgsGetCreditRequest;
import com.sgzn.sgpay.model.response.SgsResultResponse;
import com.sgzn.sgpay.model.response.vo.UserCreditVo;
import com.sgzn.sgpay.persistence.dao.TUserAccountMapper;
import com.sgzn.sgpay.persistence.domain.TUserAccount;
import com.sgzn.sgpay.persistence.domain.TUserAccountExample;
import com.sgzn.sgpay.service.SgsGetCreditService;
import com.sgzn.sgpay.service.support.SgsResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 查询用户积分
 * @author huangsenguang
 */
@Slf4j
@Service
public class SgsGetCreditServiceImpl implements SgsGetCreditService {
    @Autowired
    private TUserAccountMapper tUserAccountMapper;

    @Override
    public SgsResultResponse<UserCreditVo> getCredit(SgsGetCreditRequest request) {
        try{
            UserCreditVo vo = handleCredit(request.getUserId());
            return SgsResponseUtil.INSTANCE.success(vo);
        }catch (Exception e){
            log.error("查询积分：user is not exist!");
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc());
        }
    }

    private UserCreditVo handleCredit(String userId) {
        TUserAccountExample tUserAccountExample = new TUserAccountExample();
        TUserAccountExample.Criteria tUserAccountExampleCriteria = tUserAccountExample.createCriteria();
        tUserAccountExampleCriteria.andUserIdEqualTo(userId);
        List<TUserAccount> tUserAccounts = this.tUserAccountMapper.selectByExample(tUserAccountExample);
        UserCreditVo userCreditVo = new UserCreditVo();
        if (CollectionUtils.isNotEmpty(tUserAccounts)) {
            TUserAccount tUserAccount = tUserAccounts.get(0);
            userCreditVo.setCredit(tUserAccount.getAccountAmount().toString());
        }
        userCreditVo.setUserId(userId);
        return userCreditVo;
    }
}

